#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <stdlib.h>

int main(int argc, char const *argv[])
{
    int childPid;
    int id;
    int i;
    char buf[10];
    char *ptr;
    int totalbytes = 0;
    if ((childPid = fork()) == -1) {
        perror("fork");
        exit(EXIT_FAILURE);
    }
    if (childPid == 0) { // 子进程
        if ((id = shmget((key_t)12345, 50*sizeof(char), IPC_CREAT|0666)) == -1) {
            perror("创建共享内存失败");
            exit(EXIT_FAILURE);
        }
        printf("id：%d\n", id);
        if ((ptr = (char *) shmat(id, NULL, 0)) == NULL) { // 挂载
            if (shmctl(id, IPC_RMID, NULL) == -1) {
                perror("删除共享内存失败");
            }
            exit(EXIT_FAILURE);
        }
        for (i=0; argv[1][i]!='\0'; i++) {
            *ptr = argv[1][i];
            ptr++;
        }
        printf("this is child.\nwrite argv[1] to shm. count: %d\n", i);
        exit(EXIT_SUCCESS);
            
    } else if (childPid > 0) { // 父进程
        wait(0); // 等待子进程执行完
        if ((id = shmget((key_t)12345, 50*sizeof(char), IPC_CREAT|0666)) == -1) {
            perror("father创建共享内存失败");
            exit(EXIT_FAILURE);
        }
        if ((ptr = (char *) shmat(id, NULL, 0)) == NULL) { // 挂载
            if (shmctl(id, IPC_RMID, NULL) == -1) {
                perror("father删除共享内存失败");
            }
            exit(EXIT_FAILURE);
        }
        printf("this is parent.\ninput charater is %s\n", ptr);
        if (shmctl(id, IPC_RMID, NULL) == -1) {
            perror("father 无法删除共享内存");
            exit(EXIT_FAILURE);
        }
        exit(EXIT_SUCCESS);
    }else {
        perror("创建子进程失败");
        exit(EXIT_FAILURE);
    }

    return 0;
}
